package com.example.boot6rabbitmqbalance.listener;

import com.alibaba.fastjson.JSONObject;

import com.example.boot6rabbitmqbalance.bean.Message;
import com.example.boot6rabbitmqbalance.rabbitmq.RabbitmqSender;
import com.example.boot6rabbitmqbalance.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

@Slf4j
@Component
public class MessageListener {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    OrderService orderService;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Autowired
    RabbitmqSender rabbitmqSender;

    @RabbitListener(queues = "jack.message")
    public void process(String strmsg) {

        final Message message = JSONObject.parseObject(strmsg,Message.class);
        log.info("===========开始消费支付宝的消息============" + JSONObject.toJSONString(message));
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                int messageId = message.getMessage_id();
                int i = orderService.queryMessageCountByMessageId(messageId);

                if (i == 0) {
                    orderService.updateAmount(message.getAmount(), message.getUser_id());
                    orderService.insertMessage(message.getUser_id(), message.getMessage_id(), message.getAmount());
                } else {
                    logger.info("异常转账");
                }
                return null;
            }
        });

        //回调支付宝修改状态接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("messageId", message.getMessage_id());
        jsonObject.put("respCode", "ok");
        log.info("=================发送转账成功应答消息给支付宝==============" + jsonObject.toJSONString());
        rabbitmqSender.sendMessage("exchange.message.response","jack.message.routeKey.response",jsonObject.toJSONString());
    }
}
